﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoachingOrganizer.Database.DataAccess;
using CoachingOrganizer.ClientInfrastructure.ServicesEntities.LocalStorage.Tools.EmotionsPack;
using CoachingOrganizer.Toolkit.Events;

namespace CoachingOrganizer.Database.DataAccessLayer.Tools.EmotionsPack
{
    public class EmotionTraceItemDAL : IEmotionTraceItemInfo
    {
        private readonly DbManagerBase _dbManager;
        private EmotionTraceItemDA _da;
        private string _emotionName;
        private string _traceItemName;
        private byte[] _tracePicture;

        public string EmotionName
        {
            get { return _emotionName; }
            set { _emotionName = value; }
        }

        public string TraceItemName
        {
            get { return _traceItemName; }
            set { _traceItemName = value; }
        }

        public byte[] TracePicture
        {
            get { return _tracePicture; }
            set { _tracePicture = value; }
        }

        public EmotionTraceItemDAL(DbManagerBase dbManager)
        {
            _dbManager = dbManager;
        }

        public EmotionTraceItemDA CreateNewDA(EmotionsPackDA emotionsPack)
        {
            return _da = new EmotionTraceItemDA()
            {
                EmotionsPackId = emotionsPack.Id,
                EmotionName = _emotionName
            };
        }

        public ActionResult Save()
        {
            _da.TraceItemName = _traceItemName;
            _da.TracePicture = _tracePicture;
            return _dbManager.SafeRun(() => _dbManager.Context.InsertOrReplace(_da));
        }

        public bool Load(int id)
        {
            EmotionTraceItemDA emotionTraceItem = _dbManager.Context.Find<EmotionTraceItemDA>(da => da.Id == id);
            if (emotionTraceItem == null)
                return false;
            Load(emotionTraceItem);
            return true;
        }

        public void Load(EmotionTraceItemDA emotionTraceItem)
        {
            _da = emotionTraceItem;
            _emotionName = _da.EmotionName;
            _traceItemName = _da.TraceItemName;
            _tracePicture = _da.TracePicture;
        }

        public ActionResult Remove()
        {
            if (_da != null)
                _dbManager.SafeRun(() => _dbManager.Context.Delete<EmotionTraceItemDA>(_da.Id));
            return ActionResult.GetErrorResult(new KeyNotFoundException());
        }
    }
}